﻿using System.Collections.Generic;
using System.Web.Mvc;
using Beeldbankmvc.Helpers;
using Beeldbankmvc.Models;
using Beeldbankmvc.ViewModels;

namespace Beeldbankmvc.Controllers
{
    [HandleErrorWithELMAH]
    public class OrderController : Controller
    {
        OrderRepository orderRepository = new OrderRepository();

        //
        // GET: /Order/
        [Authorize(Roles = "Administrator")]
        public ActionResult Index()
        {
            // Get all orders as model
            var orderViewModel = orderRepository.getSortedOrders();

            return View(orderViewModel);
        }

        //
        // GET: /Order/Details/5
        [Authorize(Roles = "Administrator")]
        public ActionResult Details(int? id)
        {
            if (id == null)
                return new FileNotFoundResult { Message = "No order found due to invalid id" };

            OrderViewModel order = orderRepository.FindOne(id.Value);
            if (order == null)
                return new FileNotFoundResult { Message = "No order found for id=" + id };

            List<BEELDBANK_ORDERREGEL> orderregelList = new List<BEELDBANK_ORDERREGEL>();
            orderregelList.AddRange(orderRepository.FindAllItemsFromOrder(order.Id));

            order.orderregelObjects = orderregelList;

            return View(order);
        }

        //
        // GET: /Order/Delete/5
        [Authorize(Roles = "Administrator")]
        public ActionResult Delete(int id)
        {
            OrderViewModel order = orderRepository.FindOne(id);
            if (order == null)
                return new FileNotFoundResult { Message = "No order found for id=" + id };

            List<BEELDBANK_ORDERREGEL> orderregelList = new List<BEELDBANK_ORDERREGEL>();
            orderregelList.AddRange(orderRepository.FindAllItemsFromOrder(order.Id));

            order.orderregelObjects = orderregelList;

            return View(order);
        }

        //
        // POST: /Order/Delete/5

        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                orderRepository.Delete(id);
                orderRepository.Save();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
